<template>
	<view id="box">
		<u-toast ref="uToast"></u-toast>
		<image class="icon_img" src="@/static/images/nav_icon.svg"></image>
		<view class="login">
			<uni-forms ref="form" :modelValue="formData" :rules="rules">
				<uni-forms-item required label="手机号" name="phone">
					<uni-easyinput :inputBorder="false" type="text" v-model="formData.phone" placeholder="请输入手机号" maxlength="11"/>
				</uni-forms-item>
				<uni-forms-item v-if="!isQuickLogin" required label="密码" name="password">
					<uni-easyinput :inputBorder="false" type="password" v-model="formData.password" placeholder="请输入密码" maxlength="18"></uni-easyinput>
				</uni-forms-item> 
				<uni-forms-item v-if="isQuickLogin" required label="验证码" name="code">
					<uni-easyinput :inputBorder="false" type="number"
						v-model="formData.code" placeholder="请输入验证码" maxlength="6" clearSize="0"/>
					<text class="send_code" v-if="isQuickLogin" @click="sendCode">{{content}}</text>
				</uni-forms-item>
			</uni-forms>
		</view>
		<view class="login_center">
			<view style="overflow: hidden;">
				<text class="left" v-if="!isQuickLogin" @click="toPhonePwdLogin">快速登录/注册</text>
				<text class="left" v-if="isQuickLogin" @click="toPhonePwdLogin">
					密码登录
				</text>
				<text class="right" @click="forgetPassword">忘记密码？</text>
			</view>
			<view class="login_center_btn">
				<button @click="formSubmit" class="login_btn" style="border-radius: 45px;">登录</button>
				<view class="create_user" @click="createUser">创建用户</view>
				<view>其他登录方式</view>
				<view class="other_user" style="overflow: hidden;">
					<text class="weixin_img">
						<image @click="WXLogin" class="icon_img" src="@/static/images/weixindenglu.svg"></image>
					</text>
					<text class="qq_img">
						<image @click="QQLogin" class="icon_img" src="@/static/images/QQdenglu_1.svg"></image>
					</text>
				</view>
			</view>
		</view>
		<view class="register">
			<view class="re_center">
				<text class="register_text">注册即代表你同意</text>
				<view v-model='formData.phone'></view>
				<view class="register_btn" @click="toUserAgreement">《思云课堂用户服务协议》</view>
			</view>
		</view>
	</view>
</template>
<script>
	
	import {getLogin} from '@/static/http/getData.js'
	
	import {getLoginCode} from '@/static/http/getData.js'
	
	import {getLoginByPhone} from '@/static/http/getData.js'
	
	import {getLoginByWX} from '@/static/http/getData.js'
	
	import {getLoginByQQ} from '@/static/http/getData.js'
	
	export default {
		data() {
			return {
				formData: {
					phone: '',
					password: '',
					code:'',
				},
				//快速登录
				isQuickLogin: false,
				isCode: false,
				keyword: '',
				//定时器
				timer: '',
				content: '获取验证码',
				//验证码
				code: '',
				//倒计时
				timeout: 60,
				rules: {
					// 对phone字段进行必填验证
					phone: {
						rules: [{
								required: true,
								errorMessage: '请输入手机号',
							},
							{
								pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
								errorMessage: '请输入正确手机号',
							}
						]
					},
					// 对password字段进行必填验证
					password: {
						rules: [
							{
								required: true,
								errorMessage: '请输入密码',
							}, 
							/* {
								pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\\W]{6,18}$/,
								errorMessage: '密码长度为6-18位',
							} */
						]
					},
					// 对code字段进行必填验证
					code: {
						rules: [
							{
								required: true,
								errorMessage: '请输入验证码',
							},
						],
					}
				}
			}
		},
		methods: {
			//登录成功-跳转首页
			jumpIndex(){
				var beforeUser = JSON.parse(uni.getStorageSync('beforeUser'));
				if(beforeUser != null){
					uni.switchTab({
						url:'/pages/index/index'
					})
				}
			},
			clearForm(){
				//提交后清空表单 
				this.formData.phone = '';
				this.formData.password = '';
				this.formData.code = '';
			},
			//登录成功的回调
			loginSuccess(res){
				uni.showToast({
					title: '登录中',
					icon: 'loading',
					duration: 2000
				})
				//延迟1秒执行
				this.loginTimer = setTimeout(() => {
					uni.showToast({
						title: '登录成功',
						duration: 1000 
					}) 
					//存储登录信息
					uni.setStorageSync('beforeUser',JSON.stringify(res.data.data));
					setTimeout(() => {
						this.jumpIndex();
					},1000)
				},1000)
			},
			//验证码登录和密码登录切换
			toPhonePwdLogin(){
				this.code = '';
				this.isQuickLogin = !this.isQuickLogin;
			},
			//发送短信验证码
			sendCode(){
				this.$refs.form.validateField(['phone']).then(res => {
					if(this.timeout == 60){
						getLoginCode().then(res => {
							this.code = res.data.data;
							console.log(this.code);
							if(this.code != ''){ 
								var params = {
									type: 'default',
									message: this.code,
								}
								console.log(this.code);
								this.$refs.uToast.show({
									...params
								})
							}
						})
						this.getTimeOut();
					}
				}).catch(err => {
					//移除表单的验证结果
					this.$refs.form.clearValidate(['phone', 'password']);
					uni.showToast({
						title:'请输入手机号',
						icon:'error',
						duration: 2000
					})
				})
			},
			//定时器
			getTimeOut(){
				this.timer = setInterval(()=>{
					this.content = this.timeout + '秒后重新发送';
					this.timeout--;
					if(this.timeout < 0){
						this.timeout = 60;
						this.content = '重新发送验证码';
						//停止定时器 
						clearInterval(this.timer);
					}
				},1000)
			},
			//登录
			formSubmit(e){
				this.$refs.form.validate().then(res=>{
					this.$refs.form.clearValidate(['phone', 'password', 'code']);
					console.log("开始登录");
					if(this.code != ''){
						console.log("走验证码");
						if(this.timeout != 60){
							if(this.formData.code == this.code){
								this.clearForm();
								this.formData = {
									phone: res.phone
								}
								getLoginByPhone(this.formData).then(res => {
									if(res.data.data != null){
										console.log(res.data.data);
										switch(res.data.data.status){
											case 2://正常
												this.loginSuccess(res);
												break;
											case 4://注销
												uni.showToast({
													title: '该账号已被注销',
													icon: 'error',
													duration: 2000
												})
												break;
											case 5://封停
												uni.showToast({
													title: '该账号已被封停',
													icon: 'error',
													duration: 2000
												})
												break;
										}
									}else{
										uni.showToast({
											title: '登录失败',
											icon: 'error',
											duration: 2000
										})
									}
								})
							}else{
								uni.showToast({
									title: '验证码错误',
									icon: 'error',
									duration: 2000
								})
							}
						}else{
							uni.showToast({
								title: '验证码失效',
								icon: 'error',
								duration: 2000
							})
						}
					}else {
						this.clearForm();
						console.log('密码登录');
						//密码登录
						this.formData = {
							phone: res.phone,
							password: res.password
						}
						getLogin(this.formData).then(res => {
							console.log('进入密码登录');
							if(res.data.data != null){
								switch(res.data.data.status){
									case 2://正常
										this.loginSuccess(res);
										break;
									case 4://注销
										uni.showToast({
											title: '该账号已被注销',
											icon: 'error',
											duration: 2000
										})
										break;
									case 5://封停
										uni.showToast({
											title: '该账号已被封停',
											icon: 'error',
											duration: 2000
										})
										break;
								}
							}else{
								uni.showToast({
									title: '账号或密码错误',
									icon: 'error',
									duration: 2000
								})
							}
						})
					}
				}).catch(err => {
					uni.showToast({
						title: '账号或密码不为空',
						icon: 'error',
						duration: 2000 
					})
					this.$refs.form.clearValidate(['phone', 'password','code'])
				})
			},
			//微信登录
			WXLogin(){
				//由于this作用域问题，事先使用that存储this
				let that = this;
				uni.login({
					provider: 'weixin',
					success: function (loginRes) {
						//登录成功返回信息
						console.log(loginRes.authResult);
						uni.getUserInfo({ 
							provider: 'weixin',
							success:function(res){
								that.clearForm();
								var sex;
								if(res.userInfo.gender == '0'){
									sex = 1//男
								}else if(res.userInfo.gender == '1'){
									sex = 2//女 
								}
								var data = {
									openId: res.userInfo.openId,
									nickname: res.userInfo.nickName,
									avatarUrl: res.userInfo.avatarUrl,
									sex: sex, 
								}
								console.log(data);
								getLoginByWX(data).then((res) => {
									console.log(res.data.data.status);
									switch(res.data.data.status){
										case 2://正常
											that.loginSuccess(res);
											break;
										case 4://注销 
											uni.showToast({
												title: '该账号已被注销',
												icon: 'error',
												duration: 2000
											}) 
											break;
										case 5://封停
											uni.showToast({
												title: '该账号已被封停',
												icon: 'error',
												duration: 2000
											})
											break;
									}
								});
							} 
						})
					}
				});
			},
			//QQ登录
			QQLogin(){
				//由于this作用域问题，事先使用that存储this
				let that = this;
				uni.login({
					provider: 'qq',
					success: function (loginRes) {
						//登录成功返回信息
						console.log(loginRes.authResult);
						uni.getUserInfo({
							provider: 'qq', 
							success:function(res){
								that.clearForm();
								var sex;
								if(res.userInfo.gender == '男'){
									sex = 1//男
								}else if(res.userInfo.gender == '女'){
									sex = 2//女
								}
								var data = {
									openId: res.userInfo.openId,
									nickname: res.userInfo.nickName,
									avatarUrl: res.userInfo.avatarUrl,
									sex: sex,
								}
								console.log(data.sex);
								getLoginByQQ(data).then((res) => {
									console.log(res.data.data);
									switch(res.data.data.status){
										case 2://正常
											that.loginSuccess(res);
											break;
										case 4://注销
											uni.showToast({
												title: '该账号已被注销',
												icon: 'error',
												duration: 2000
											})
											break;
										case 5://封停
											uni.showToast({
												title: '该账号已被封停',
												icon: 'error',
												duration: 2000
											})
											break;
									}
								});
							}
						})
					}
				}); 
			},
			//用户服务协议
			toUserAgreement(){
				uni.navigateTo({
					url:'/pages/login/user-agreement'
				})
			},
			//创建用户
			createUser(){
				uni.navigateTo({
					url:'/pages/login/user-create'
				})
			},
			//重置密码
			forgetPassword(){
				uni.navigateTo({
					url: '/pages/login/forget-password'
				});
			}
		},
	}
</script>

<style lang="scss" scoped>
	*{
		margin: 0;
		padding: 0;
	}
	#box {
		width: 84%;
		margin: 0 auto;
		text-align: center;
	}
	.create_user{
		width: 100px;
		margin: 20px auto;
	}
	.register_text{
		color: #B2B1AF;
	}
	.icon_img{
		width: 70px;
		height: 70px;
		margin: 20% auto;
	}
	.login_center .left{
		float: left;
		color: #619C96;
	}
	.login_center .right{
		float: right;
		color: #8F9897;
	}
	.login_center .login_btn{
		margin-top: 20px;
		background-color: #1ABC9C;
		color: #fff;
	}
	.login_center .login_center_btn{
		width: 100%;
		text-align: center;
	}
	.login_center .login_center_btn view{
		margin-top: 20px;
		font-size: 17px;
		color: #B2B1AF;
	}
	.login_center .login_center_btn :nth-child(2){
		color: #619C96;
	}
	.login_center .login_center_btn .other_user .icon_img{
		width: 60px;
		height: 60px;
	}
	.login_center .login_center_btn .other_user .weixin_img{
		float: left;
		margin-left: 15%;
		//margin-top: 5%;
	}
	.login_center .login_center_btn .other_user .qq_img{
		float: right;
		margin-right: 15%;
		//margin-top: 5%;
	}
	.register{
		margin-top: 20px;
	}
	.register .re_center{
		text-align: center;
	}
	.register .re_center .register_btn{
		color: #617AA1;
	}
	.send_code{
		position: absolute;
		top: 7px;
		right: 0px;
		color: #1ABC9C;
	}
	.code_time {
		position: absolute;
		top: 7px;
		right: 0;
		color: #999999;
	}
</style>
